import Vue from 'vue'
import Router from 'vue-router'
import { cloneDeep } from 'lodash'
import { getItemById } from '@/utils/methods'
import { getStorage } from '@/utils/localStorage'

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)
const constantRoutes = [
    {
        path: '/',
        component: () => import('./index'),
        redirect: '/home',
        name: 'root',
        children: [
            {
                path: '/home',
                component: () => import('./home/index'),
                name: 'home',
                meta: {
                    icon: 'home',
                },
            },
            {
                path: '/SelfEvaluation',
                component: () => import('./SelfEvaluation/index'),
                name: 'SelfEvaluation',
                meta: {
                    icon: 'file',
                },
            },
            {
                path: '/setting',
                component: () => import('./setting/index'),
                name: 'setting',
                redirect: '/notChild',
                meta: {
                    icon: 'set',
                },
                children: [
                    {
                        path: '/setting/menus',
                        component: () => import('./setting/menus'),
                        name: 'menus',
                    },
                    {
                        path: '/setting/users',
                        component: () => import('./setting/users'),
                        name: 'users',
                    },
                    {
                        path: '/setting/roles',
                        component: () => import('./setting/roles'),
                        name: 'roles',
                    },
                    {
                        path: '/setting/areas',
                        component: () => import('./setting/areas'),
                        name: 'areas',
                    },
                    {
                        path: '/setting/selfEvaluationTemplate',
                        component: () => import('./setting/selfEvaluationTemplate/index'),
                        name: 'selfEvaluationTemplate',
                    },
                ],
            },
            {
                path: '/qa',
                component: () => import('./qa/index'),
                name: 'qa',
                meta: {
                    icon: 'help',
                },
            },
            {
                path: '/credit',
                component: () => import('./credit/index'),
                name: 'credit',
                meta: {
                    icon: 'user minus-fill',
                },
            },
            {
                path: '/policy',
                component: () => import('./policy/index'),
                name: 'policy',
                meta: {
                    icon: 'book',
                },
            },
            {
                path: '/notice',
                component: () => import('./notice/index'),
                name: 'notice',
                meta: {
                    icon: 'book',
                },
            },
            {
                path: '/message',
                component: () => import('./message/index'),
                name: 'message',
                meta: {
                    icon: 'message',
                },
            },
            {
                path: '/applyManage',
                component: () => import('./applyManage/index'),
                name: 'applyManage',
                redirect: '/Apply',
                meta: {
                    icon: 'system-setting',
                },
                children: [
                    {
                        path: '/applyManage/Apply',
                        component: () => import('./applyManage/Apply'),
                        name: 'Apply',
                    },
                    {
                        path: '/applyManage/Check',
                        component: () => import('./applyManage/Check'),
                        name: 'Check',
                    },
                ],
            },
            {
                path: '/statistics',
                component: () => import('./statistics/index'),
                name: 'statistics',
                meta: {
                    icon: 'data-pie',
                },
            },
            {
                path: '/statisticsCity',
                component: () => import('./statistics/city'),
                name: 'statisticsCity',
                meta: {
                    icon: 'data-pie',
                },
            },
            {
                path: '/statisticsPro',
                component: () => import('./statistics/pro'),
                name: 'statisticsPro',
                meta: {
                    icon: 'data-pie',
                },
            },
        ],
    },
]

const createRouter = () => {
    return new Router({
        routes: [
            {
                path: '/login',
                component: () => import('./user/Login.vue'),
                name: 'login',
            },
            {
                path: '/preview',
                component: () => import('./preview.vue'),
                name: 'preview',
            },
            {
                path: '/register',
                component: () => import('./user/Register.vue'),
                name: 'register',
            },
            {
                path: '/403',
                component: () => import('./403.vue'),
            },
            {
                path: '/notChild',
                component: () => import('./notChild.vue'),
                name: 'notChild',
            },
            {
                path: '*',
                component: () => import('./404.vue'),
            },
        ],
    })
}

const router = createRouter()

const resetRouter = function () {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher
}
const addRoutes = userInfo => {
    resetRouter()
    let menus = []
    if (!userInfo) {
        const value = getStorage('userInfo')
        console.log(value, 'value')
        if (value) {
            menus = value.menus
        }
    } else {
        menus = userInfo.menus
    }
    console.log(menus, 'menus')
    // 用户权限router值的集合
    const routerValues = {}
    const getRouterValues = menus => {
        menus.forEach(({ children, router, label }) => {
            routerValues[router] = label
            if (children?.length) {
                getRouterValues(children)
            }
        })
    }
    getRouterValues(menus)
    console.log(routerValues, 'routerValues')
    // 从all路由里删除不在权限内的
    const getFilterRoutes = routes => {
        for (let i = routes.length - 1; i >= 0; i--) {
            const item = routes[i]
            // 删除不在用户权限内的
            if (!Object.keys(routerValues).includes(item.name)) {
                routes.splice(i, 1)
            } else if (item.children?.length) {
                getFilterRoutes(item.children)
            }
        }
    }
    let purviewRoutes = cloneDeep(constantRoutes)
    purviewRoutes.forEach(item => {
        if (item.path === '/') {
            if (item.children?.length) {
                getFilterRoutes(item.children)
            }
        }
    })
    // 在权限路由里 设置重定向/title/promiseBtns
    const formatPurviewRoutes = routes => {
        routes.forEach(item => {
            const menu = getItemById(menus, item.name, 'router')
            if (item.meta) {
                item.meta.title = routerValues[item.name]
                item.meta.promiseBtns = menu.promiseBtns
            } else {
                item.meta = {
                    title: routerValues[item.name],
                    promiseBtns: menu.promiseBtns,
                }
            }
            if (item.children && item.children.length) {
                // 重定向到menus该级的第一个有权限的子级
                const purviewNames = item.children.map(({ name }) => name)
                const menuFirstChild = menu.children.find(({ router }) => purviewNames.includes(router)) || {}
                // 再从purview找到path
                console.log(menuFirstChild, 'firstChild')
                const redirectPath = (item.children.find(({ name }) => name === menuFirstChild.router) || {}).path
                item.redirect = redirectPath
                formatPurviewRoutes(item.children)
            }
        })
    }
    purviewRoutes.forEach(item => {
        if (item.path === '/') {
            if (item.children?.length) {
                // 根路径重定向到有权限的
                const purviewNames = item.children.map(({ name }) => name)
                const menuFirst = menus.find(({ router }) => purviewNames.includes(router)) || {}
                const redirectPath = (item.children.find(({ name }) => name === menuFirst.router) || {}).path
                item.redirect = redirectPath
                formatPurviewRoutes(item.children)
            } else {
                item.redirect = '/login'
            }
        }
    })
    console.log(purviewRoutes, 'purviewRoutes')
    router.options.routes = [...router.options.routes, ...purviewRoutes]
    purviewRoutes.forEach(item => {
        router.addRoute(item)
    })
}

addRoutes()

//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    console.log(router)
    const isLogin = localStorage.getItem('isLogin')
    // const isLogin = true
    if (!isLogin && to.path !== '/login' && to.path !== '/register') {
        next('/login')
    } else {
        next()
    }
})

export { addRoutes, resetRouter }
export default router
